﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;

namespace GeuERP.Common
{
    public static class GetApiResult
    {
        //调用方法如下
        //ApiResult apiResult = GetApiResult.HttpGet("", "LoginCheck", $"dbType=DB02&loginCode={userCode}&fromType=2&Pwd={textBox2.Text.Trim()}");

        /// <summary>
        /// </summary>
        /// <param name="token">      </param>
        /// <param name="apiUrl">     </param>
        /// <param name="queryString"></param>
        /// <returns></returns>
        public static ApiResult HttpGet(string ApiGetWayUrl, string token, string apiUrl, string queryString)
        {
            string url;
            if (!string.IsNullOrEmpty(queryString))
            {
                url = ApiGetWayUrl + apiUrl + "?" + queryString;
            }
            else
            {
                url = ApiGetWayUrl + apiUrl;
            }
            HttpWebRequest httpRequset = (HttpWebRequest)HttpWebRequest.Create(url);//创建HTTP请求
            httpRequset.Method = "GET";//GET/POST提交
            httpRequset.Headers["token"] = token;
            httpRequset.KeepAlive = true;
            httpRequset.UserAgent = "FROM GeuERP Disktop";
            httpRequset.Accept = "text/html,application/xhtml+xml,*/*";
            httpRequset.ContentType = "text/plain;charset=utf-8";
            HttpWebResponse httpResponse = (HttpWebResponse)httpRequset.GetResponse();
            string responseString;
            using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                responseString = streamReader.ReadToEnd();
            }
            return JsonConvert.DeserializeObject<ApiResult>(responseString) as ApiResult;
        }

        //调用方法如下
        //    Hashtable ht = new Hashtable();
        //    ht.Add("dbType", "DB02");
        //    ht.Add("loginCode", userCode);
        //    ht.Add("fromType", 2);
        //    ht.Add("Pwd", textBox2.Text.Trim());
        //    ApiResult apiResult = GetApiResult.GetHttpPostDic("", "LoginCheck", ht);

        /// <summary>
        /// </summary>
        /// <param name="token">         </param>
        /// <param name="apiUrl">        </param>
        /// <param name="postDataString"></param>
        /// <returns></returns>
        public static ApiResult HttpPost(string ApiGetWayUrl, string token, string apiUrl, Hashtable postDataString)
        {
            HttpWebRequest httpRequset = (HttpWebRequest)HttpWebRequest.Create(ApiGetWayUrl + apiUrl);//创建HTTP请求
            httpRequset.Method = "POST";//GET/POST提交
            httpRequset.Headers["token"] = token;
            httpRequset.KeepAlive = true;
            httpRequset.UserAgent = "FROM GeuERP Web";
            httpRequset.Accept = "text/html,application/xhtml+xml,*/*";
            httpRequset.ContentType = "application/x-www-form-urlencoded";
            if (postDataString != null)
            {
                byte[] vs = GetJointBOfParams(postDataString);
                httpRequset.ContentLength = vs.Length;
                Stream myRequestStream = httpRequset.GetRequestStream();
                myRequestStream.Write(vs, 0, vs.Length);
                myRequestStream.Close();
            }
            HttpWebResponse httpResponse = (HttpWebResponse)httpRequset.GetResponse();
            string responseString;
            using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                responseString = streamReader.ReadToEnd();
            }
            return JsonConvert.DeserializeObject<ApiResult>(responseString) as ApiResult;
        }

        //调用方法如下
        //    Hashtable ht = new Hashtable();
        //    ht.Add("dbType", "DB02");
        //    ht.Add("loginCode", userCode);
        //    ht.Add("fromType", 2);
        //    ht.Add("Pwd", textBox2.Text.Trim());
        //    Dictionary<string, object> apiResult = GetApiResult.GetHttpPostDic("", "LoginCheck", ht);
        //    string code = apiResult["code"].ToString().Trim();取值

        /// <summary>
        /// 调用webapi
        /// </summary>
        /// <param name="token">         </param>
        /// <param name="apiUrl">        </param>
        /// <param name="postDataString"></param>
        /// <returns></returns>
        public static JArray GetHttpPostDic(string ApiGetWayUrl, string token, string apiUrl, Hashtable postDataString)
        {
            HttpWebRequest httpRequset = (HttpWebRequest)HttpWebRequest.Create(ApiGetWayUrl + apiUrl);//创建HTTP请求
            httpRequset.Method = "POST";//GET/POST提交
            httpRequset.Headers["token"] = token;
            httpRequset.KeepAlive = true;
            httpRequset.UserAgent = "FROM GeuERP Web";
            httpRequset.Accept = "text/html,application/xhtml+xml,*/*";
            httpRequset.ContentType = "application/x-www-form-urlencoded";
            if (postDataString != null)
            {
                byte[] vs = GetJointBOfParams(postDataString);
                httpRequset.ContentLength = vs.Length;
                Stream myRequestStream = httpRequset.GetRequestStream();
                myRequestStream.Write(vs, 0, vs.Length);
                myRequestStream.Close();
            }
            HttpWebResponse httpResponse = (HttpWebResponse)httpRequset.GetResponse();
            string responseString;
            using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                responseString = streamReader.ReadToEnd();
            }
            JArray ja = null;
            try
            {
                ja = (JArray)JsonConvert.DeserializeObject(responseString);
            }
            catch
            {
            }
            return ja;
        }

        /// <summary>
        /// </summary>
        /// <param name="token">         </param>
        /// <param name="apiUrl">        </param>
        /// <param name="postDataString"></param>
        /// <returns></returns>
        public static string HttpPostFile(string ApiGetWayUrl, string token, string apiUrl, string fileName)
        {
            HttpWebRequest httpRequset = (HttpWebRequest)HttpWebRequest.Create(ApiGetWayUrl + apiUrl);//创建HTTP请求
            string strBoundary = "---------" + DateTime.Now.Ticks.ToString("x");

            httpRequset.Method = "POST";//GET/POST提交
            httpRequset.Headers["token"] = token;
            httpRequset.KeepAlive = true;
            httpRequset.UserAgent = "FROM GeuERP Web";
            httpRequset.Accept = "text/html,application/xhtml+xml,*/*";
            httpRequset.ContentType = "multipart/form-data; boundary=" + strBoundary;
            using (WebClient wc = new WebClient())
            {
                return System.Text.Encoding.UTF8.GetString(wc.UploadFile(ApiGetWayUrl, fileName));
            }
        }

        #region 内部私有方法

        private static byte[] GetJointBOfParams(Hashtable paramsOfUrl)
        {
            // 编辑并Encoding提交的数据
            string stringJointOfParams = GetJointSOfParams(paramsOfUrl);
            byte[] data = new UTF8Encoding().GetBytes(stringJointOfParams);
            return data;
        }

        private static string GetJointSOfParams(Hashtable paramsOfUrl)
        {
            if (paramsOfUrl == null || paramsOfUrl.Count == 0) return string.Empty;
            // 编辑并Encoding提交的数据
            StringBuilder sbuilder = new StringBuilder();
            int i = 0;
            foreach (DictionaryEntry de in paramsOfUrl)
            {
                string value = ToHttpChar(de.Value.ToString());
                if (i == 0)
                {
                    sbuilder.Append(de.Key + "=" + value);
                }
                else
                {
                    sbuilder.Append("&" + de.Key + "=" + value);
                }
                i++;
            }
            return sbuilder.ToString();
        }

        private static string ToHttpChar(string value)
        {
            value = value.ToString().Replace("+", "%2B");
            value = value.ToString().Replace(" ", "%20");
            value = value.ToString().Replace("/", "%2F");
            value = value.ToString().Replace("?", "%3F");
            value = value.ToString().Replace("%", "%25");
            value = value.ToString().Replace("#", "%23");
            value = value.ToString().Replace("&", "%26");
            value = value.ToString().Replace("=", "%3D");
            value = value.ToString().Replace(@"\", "%5C");
            value = value.ToString().Replace(".", "%2E");
            value = value.ToString().Replace(":", "%3A");
            return value;
        }

        #endregion 内部私有方法
    }

    /// <summary>
    /// Api返回结果
    /// </summary>
    public class ApiResult
    {
        /// <summary>
        /// 请求结果码
        /// </summary>
        public ResultCodeType Code { set; get; }

        /// <summary>
        /// 请求结果数据区
        /// </summary>
        public List<JObject> Data { set; get; }

        /// <summary>
        /// 请求结果信息
        /// </summary>
        public string Msg { set; get; }

        /// <summary>
        /// Objcet转换JObcet
        /// </summary>
        /// <param name="obj">要转换的Object</param>
        /// <returns></returns>
        public static JObject ObjToJObj<T>(T obj)
        {
            if (obj == null)
            {
                return null;
            }
            else
            {
                return JObject.FromObject(obj);
            }
        }

        public static List<JObject> ListObjToListJObj<T>(List<T> listObj)
        {
            if (listObj == null)
            {
                return null;
            }
            else
            {
                List<JObject> rt = new List<JObject>();
                foreach (var obj in listObj)
                {
                    rt.Add(JObject.FromObject(obj));
                }
                return rt;
            }
        }

        /// <summary>
        /// 将ApiResult对象转json字符串，json字符串的key按照小驼峰命名
        /// </summary>
        /// <param name="apiResult">要转换的Object</param>
        /// <returns>转换后的json字符串</returns>
        public static string ApiResultToJsonString(ApiResult apiResult)
        {
            var serializerSettings = new JsonSerializerSettings
            {
                // 设置为驼峰命名
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };
            return JsonConvert.SerializeObject(apiResult, Formatting.None, serializerSettings);
        }

        /// <summary>
        /// 获取ApiResult对象
        /// </summary>
        /// <param name="resultCodeType">返回值code类型</param>
        /// <param name="resultData">    数据区数据</param>
        /// <returns>ApiResult对象</returns>
        public static ApiResult GetApiResult(ResultCodeType resultCodeType, List<JObject> resultData)
        {
            return new ApiResult
            {
                Code = resultCodeType,
                Data = resultData,
                Msg = resultCodeType.ToString()
            };
        }
    }

    /// <summary>
    /// api返回结果定义
    /// </summary>
    public enum ResultCodeType
    {
        Success = 200,//请求成功
        PassError = 401,//密码错误，拒绝登录
        Forbidden = 403,//未授权拒绝服务
        TimeOut = 408,//授权超时从新登录
        Error = 500 //服务器错误
    }
}